<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item label="物料类型" prop="materialType" >
        <el-select v-model="queryParams.materialType" placeholder="请选择状态" clearable size="small" style="width: 250px">
          <el-option value="1" label="原材料">原材料</el-option>
          <el-option value="2" label="半成品">半成品</el-option>
          <el-option value="3" label="成品">成品</el-option>
          <el-option value="4" label="辅料">辅料</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="规格型号" prop="specification">
        <el-input
          v-model="queryParams.specification"
          placeholder="请输入规格型号"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 250px"
        />
      </el-form-item><br/>
      <el-form-item label="分类名称" prop="categoryName">
        <el-select v-model="queryParams.categoryName" placeholder="请选择分类名称" clearable size="small" style="width: 250px">
          <el-option v-for="index in Category" :key="index.id" :label="index.categoryName" :value="index.categoryName">{{ index.categoryName }}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 250px">
          <el-option value="0" label="禁用">禁用</el-option>
          <el-option value="1" label="启用">启用</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:Material:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:Material:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:Material:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:Material:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="MaterialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编码" align="center" prop="materialCode" width="190"/>
      <el-table-column label="物料名称" align="center" prop="materialName" width="150"/>
      <el-table-column label="物料类型" align="center" prop="materialType" width="130">
        <template slot-scope="scope">
          <span v-if="scope.row.materialType == 1">原材料</span>
          <span v-if="scope.row.materialType == 2">半成品</span>
          <span v-if="scope.row.materialType == 3">成品</span>
          <span v-if="scope.row.materialType == 4">辅料</span>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" align="center" prop="specification" width="150"/>
      <el-table-column label="分类名称" align="center" prop="categoryName" width="140"/>
      <el-table-column label="状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">禁用</span>
          <span v-if="scope.row.status == 1">启用</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="right" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:Material:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:Material:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="物料类型" prop="materialType">
          <el-select v-model="form.materialType" placeholder="请选择物料类型" style="width:378px">
            <el-option label="原材料" value="1">原材料</el-option>
            <el-option label="半成品" value="2">半成品</el-option>
            <el-option label="成品" value="3">成品</el-option>
            <el-option label="辅料" value="4">辅料</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类名称" style="width:378px">
            <el-option v-for="item in Category" :key="item.id" :label="item.categoryName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓储单位" prop="storageUnitName">
          <el-input v-model="form.storageUnitName" placeholder="请输入仓储单位" />
        </el-form-item>
        <el-form-item label="标准单价" prop="standardPrice">
          <el-input v-model="form.standardPrice" placeholder="请输入标准单价" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" clearable size="small" style="width:378px">
            <el-option value="0" label="禁用">禁用</el-option>
            <el-option value="1" label="启用">启用</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial } from "@/api/system/Material";
import {listCategory} from '@/api/system/Category'
import category from '@/views/system/Category/index.vue'

export default {
  name: "Material",
  computed: {
    category() {
      return category
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //编号
      codeNum:null,
      // 物料表格数据
      MaterialList: [],
      //分类
      Category:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: null,
        materialType: null,
        specification: null,
        categoryName: null,
        status:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" }
        ],
        materialType: [
          { required: true, message: "物料类型不能为空", trigger: "change" }
        ],
        specification: [
          { required: true, message: "规格型号不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        storageUnitName: [
          { required: true, message: "仓储单位不能为空", trigger: "blur" }
        ],
        standardPrice: [
          { required: true, message: "标准单价不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCategoryList();
  },
  methods: {
    /** 查询物料列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.MaterialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCategoryList(){
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.Category = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        materialCode: null,
        materialName: null,
        materialType: null,
        specification: null,
        categoryId: null,
        categoryName: null,
        unitId: null,
        unitName: null,
        purchaseUnitId: null,
        purchaseUnitName: null,
        storageUnitId: null,
        storageUnitName: null,
        standardPrice: null,
        minStock: null,
        maxStock: null,
        safeStock: null,
        shelfLife: null,
        storageCondition: null,
        isBatchManaged: null,
        isSnManaged: null,
        status: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMaterial(id).then(response => {
        this.form = response.data;
        this.form.status= this.form.status.toString();
        this.form.materialType= this.form.materialType.toString();
        this.codeNum = this.form.materialCode;
        this.open = true;
        this.title = "修改物料";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            for (let i = 0; i < this.Category.length; i++) {
              if (this.form.categoryId === this.Category[i].id) {
                this.form.categoryName = this.Category[i].categoryName
              }
            }
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            for (let i = 0; i < this.Category.length; i++) {
              if (this.form.categoryId === this.Category[i].id) {
                this.form.categoryName = this.Category[i].categoryName
              }
            }
            var orderCode = getOrderCode(this.MaterialList);
            this.form.materialCode = orderCode;
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料编号为"' + ids + '"的数据项？').then(function() {
        return delMaterial(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/Material/export', {
        ...this.queryParams
      }, `Material_${new Date().getTime()}.xlsx`)
    }
  }
};


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="WLGL";
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].materialCode.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      console.log(list);
      let listCode=list[i].materialCode.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
